<template>
  <el-row>
    <el-col :span="spanRow">
      <!-- <LoadSearch /> -->
      <el-table ref="table"
                v-loading="loading"
                :data="tableData.slice((currentPage-1)*pageSize,currentPage*pageSize)"
                class="table-box"
                :row-style="isRed"
                :row-key="record => record.id"
                border
                @row-click="rowClickEv">
        <template v-for="(item, index) in tableColumn">
          <el-table-column v-if="item.prop === 'price'"
                           :key="index"
                           :prop="item.prop"
                           align="right"
                           :formatter="formatterPrice"
                           :label="item.label"
                           :width="item.width">
          </el-table-column>
          <el-table-column v-else
                           :key="index"
                           :prop="item.prop"
                           align="center"
                           :label="item.label"
                           :width="item.width">
          </el-table-column>
        </template>
        <el-table-column v-if="hidden"
                         fixed="right"
                         align="center"
                         label="操作"
                         width="110">
          <template slot-scope="scope">
            <el-button type="text"
                       size="small"
                       @click="edit(scope.$index, scope.row)">{{ '编辑' }}</el-button>
            <el-button type="text"
                       size="small"
                       @click="clearer(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination :current-page="currentPage"
                     align='right'
                     :page-sizes="[10, 20, 30, 50]"
                     :page-size="pageSize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="tableData.length"
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange">
      </el-pagination>
    </el-col>
    <el-col v-if="valueObject"
            :span="8">
      <AddLoadForm :value="row"
                   :edit-status="editStatus"
                   @add="addRow" />
    </el-col>
  </el-row>
</template>

<script>
import LoadSearch from './components/Search.vue'
import AddLoadForm from './components/AddLoadForm.vue'
// import { options } from '../options'
import { mapActions } from "vuex";
import { v4 } from 'uuid'
import { unitDesc, reduce, EditableIncludes } from '../index'

export default {
  name: 'LoadComponent',
  components: { LoadSearch, AddLoadForm },
  props: {
    specs: {
      type: Object,
      default: () => { }
    },
    valueObject: {
      type: Boolean,
      default: false
    },
    spanRow: {
      type: [String, Number],
      default: 16
    },
    bargaStatus: {
      type: [String, Number],
      default: null
    }
  },
  data () {
    return {
      tableColumn: [
        {
          prop: 'billingUnitDesc',
          label: '计费单位',
        },
        {
          prop: 'minValue',
          label: '最小值（>=）',
        },
        {
          prop: 'maxValue',
          label: '最大值（<）'
        },
        {
          prop: 'price',
          label: '价格(元)'
        }
      ],
      loading: false,
      editStatus: null,
      tableData: [],
      selectedArrData: [],
      row: {},
      pageSize: 10,
      currentPage: 1,
      address: '',
    }
  },
  computed: {
    query () {
      return this.$route.query
    },
    detail () {
      return this.specs?.detailData
    },
    initStatus () {
      return this.query.status || this.query.templateId
    },
    hidden () {
      return this.isShowDelete || !this.query.templateId
    },
    isShowDelete () {
      let haveStatus = null
      // if (this.detail?.status != 11 || this.detail?.status != 14) {
      if (EditableIncludes().includes(this.detail?.status)) {
        haveStatus = true
      } else {
        haveStatus = false
      }
      return haveStatus
    },
    load () {
      return ({ load }) => {
        return load.map(item => {
          const { billingUnit, maxValue, minValue, ...surplus } = item
          return {
            ...surplus,
            billingUnitDesc: unitDesc({ unit: billingUnit }),
            billingUnit: billingUnit,
            maxValue: maxValue,
            minValue: minValue,
            rangeValue: [minValue, maxValue],
            code: v4()
          }
        })
      }
    }
  },
  created () {
    if (this.initStatus) {
      this.tableData = this.load({ load: this.specs?.load });
    } else {
      this.tableData = []
    }
    // if (this.specs?.load) {
    //   this.tableData = this.load({ load: this.specs?.load });
    // }
  },
  methods: {
    ...mapActions({
      buffLoad: "quotation/buffLoad"
    }),
    isRed ({ row }) {
      const checkIdList = this.selectedArrData.map(item => item.code)
      if (checkIdList.includes(row.code)) {
        return {
          backgroundColor: '#fff5f1',
        }
      }
    },
    edit (index, row) {
      if (this.bargaStatus) return
      const rows = Object.assign({}, row)
      this.selectedArrData = [rows]
      this.row = { row: { ...rows, edit: true, index: index } }
      this.editStatus = true
      console.log('alsdfdf', this.row)
    },
    //pageSize改变时触发的事件
    handleSizeChange (val) {
      console.log(`每页 ${val} 条`);
      this.currentPage = 1; //始终保持第一页
      this.pageSize = val; //将改变的值赋给pageSize
    },
    //当前页码发生改变时触发的事件
    handleCurrentChange (val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val; //改变当前页码
    },
    rowClickEv (row) {
      // if (this.bargaStatus) return
      // this.selectedArrData = [row]
      // this.row = { row: row }
    },
    addRow (item) {
      const { price, billingUnit, maxValue, minValue } = item
      const row = {
        maxValue: maxValue,
        minValue: minValue,
        rangeValue: [minValue, maxValue],
        billingUnit: billingUnit,
        billingUnitDesc: unitDesc({ unit: billingUnit }),
        price: price,
        code: item?.code
      }
      let rows = Object.assign({}, row)
      if (this.bargaStatus) {
        this.tableData = reduce({ data: this.tableData, rows: [rows] })
      } else if (this.editStatus) {
        this.editStatus = false
        this.tableData.splice(item.index, 1, { ...rows, edit: false })
      } else {
        this.tableData.unshift({ ...rows, code: v4() })
        this.tableData = this.uniqueArray({ array: this.tableData })
      }
      this.buffLoad({ data: JSON.parse(JSON.stringify(this.tableData)) })
    },
    clearer (index) {
      this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.tableData.splice(index, 1)
        this.buffLoad({ data: this.tableData })
      })
    },
    uniqueArray ({ array }) {
      return array.filter((item, index, arr) => {
        return arr.findIndex(itemInner => (
          itemInner.billingUnit === item.billingUnit
          && itemInner.maxValue === item.maxValue
          && itemInner.minValue === item.minValue)) === index;
      })
    },
    formatterPrice (rows) {
      let n = '';
      n = String(rows.price);
      if (!n) return n;
      let str = n.split('.');
      let re = /\d{1,3}(?=(\d{3})+$)/g;
      let n1 = str[0].replace(re, "$&,");
      return str.length > 1 && str[1] ? `${n1}.${str[1]}` : `${n1}.00`;
    }
  }
}
</script>

<style scoped>
.el-pagination {
  padding: 8px 5px !important;
}
</style>
<style lang="scss" scoped>
/deep/ .el-table tbody tr:hover > td {
  background-color: transparent !important;
}
/deep/ .el-table .el-table__body tr .hover-row > td .el-table__cell {
  background-color: transparent !important;
}
.table-box {
  width: 99.9% !important;
  // height: 500px;
}
</style>